package com.woniu.zsd.permission.controller;


import com.github.pagehelper.PageInfo;
import com.woniu.dto.AdminInfoDto;
import com.woniu.form.*;
import com.woniu.zsd.commons.core.model.Result;
import com.woniu.zsd.permission.Permission.Permission;
import com.woniu.zsd.permission.entity.AdminInfo;
import com.woniu.zsd.permission.service.IAdminInfoService;
import com.woniu.commons.util.JwtUtil;
import com.woniu.commons.util.RedisKey;
import com.woniu.zsd.permission.utils.TokenUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author author
 * @since 2025-03-27
 */
@RestController
@RequestMapping("/admin-info")
@Api(tags = "管理员信息管理")
public class AdminInfoController {
    @Autowired
    private IAdminInfoService adminInfoService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private TokenUtil tokenUtil;

    @Autowired
    private JwtUtil jwtUtil;

    @GetMapping("/selAdminInfoById")
    @ApiOperation("根据条件查询工作人员信息")
    public Result<PageInfo<AdminInfo>> selAdminInfoById(@ApiParam (name = "saif", value = "查询条件") SelAdminInfoForm saif) {
        PageInfo<AdminInfo> pageInfo = adminInfoService.selAdminInfoById(saif);
        System.out.println(pageInfo);
        return new Result<PageInfo<AdminInfo>>().setData(pageInfo).setMsg("查询成功");
    }

    @GetMapping("/selAdminInfo")
    @ApiOperation("查询个人信息")
    public Result<AdminInfoDto> selAdminInfo(@RequestHeader String token) {
        Integer adminId = tokenUtil.getAdminId(token);
        AdminInfoDto adminInfo = adminInfoService.selAdminInfo(adminId);
        return new Result<AdminInfoDto>().setData(adminInfo).setMsg("查询成功");
    }

    @PostMapping("/login")
    @ApiOperation("登录")
    public Result login(@RequestBody LoginForm lf, HttpServletResponse response) throws Exception {
        //登录
        AdminInfo adminInfo = adminInfoService.login(lf);
        //生成双token
        HashMap<String, Object> body = new HashMap<>();
        body.put("id", adminInfo.getAdminId());
        body.put("role", adminInfo.getRole());
        String accessToken = jwtUtil.createToken(body, 30);
        String refreshToken = jwtUtil.createToken(body, 60 * 24);
        //将refreshToken保存到redis中
        stringRedisTemplate.opsForValue().set(RedisKey.ADMIN_REFRESH_TOKEN_KEY(accessToken),refreshToken,60 * 24, TimeUnit.MINUTES);
        stringRedisTemplate.opsForValue().set(RedisKey.ADMIN_ACCESS_TOKEN_KEY(adminInfo.getAdminId()), accessToken, 30, TimeUnit.MINUTES);
        //在redis中保存过期时
        stringRedisTemplate.opsForValue().set(RedisKey.ACCESS_TIME_OUT(accessToken), String.valueOf(body.get("id")), 30, TimeUnit.MINUTES);

        response.setHeader("Access-Control-Expose-Headers","token");
        response.setHeader("token", accessToken);
        return Result.getResult().setMsg("登录成功");
    }
//    @GetMapping("/test")
//    @ApiOperation("测试")
//    public Result test(@RequestHeader String token){
//        String id = String.valueOf(tokenUtil.getUserId(token));
//        String role = String.valueOf(tokenUtil.getRole(token));
//        System.out.println("adminId:"+id+"+role:"+role);
//        return Result.getResult().setMsg("测试成功");
//    }
    @GetMapping("/logout")
    @ApiOperation("退出登录")
    public Result logout(@RequestHeader String token){
        stringRedisTemplate.delete(RedisKey.ADMIN_ACCESS_TOKEN_KEY(tokenUtil.getAdminId(token)));
        stringRedisTemplate.delete(RedisKey.ADMIN_REFRESH_TOKEN_KEY(token));
        return Result.getResult().setMsg("退出登录成功");
    }

    @PostMapping("/insertAdminInfo")
    @ApiOperation("添加工作人员信息")
    public Result insertAdminInfo(@ApiParam(name = "aif", value = "添加员工表单")@RequestBody AdminInfoForm aif) {
        System.out.println("aif:"+aif);
        adminInfoService.insertAdminInfo(aif);
       return Result.getResult().setMsg("添加成功");
    }

    @PostMapping("/updateAdminInfo")
    @ApiOperation("修改工作人员信息")
    public Result updateAdminInfo(@ApiParam(name = "uaif", value = "修改工作人员信息表单")@RequestBody UpdateAdminInfoForm uaif) {
        // 调用服务层方法进行校验
        boolean isDuplicate = adminInfoService.checkDuplicateInfo(uaif.getAdminId(), uaif.getUsername(), uaif.getPhone());
        if (isDuplicate) {
            return Result.getResult().setMsg("账号或手机号已存在").setCode(400);
        }
        adminInfoService.updateAdminInfo(uaif);
        return Result.getResult().setMsg("修改成功");}

    @DeleteMapping("/deleteAdminInfoById")
    @ApiOperation("删除工作人员信息")
    @Permission("deleteAdminInfoById")
    public Result deleteAdminInfoById(@RequestParam Integer adminId,@RequestHeader String token) {
        adminInfoService.deleteAdminInfoById(adminId);
        return Result.getResult().setMsg("删除成功");
    }

    // 添加批量查询的接口
    @PostMapping("/selectAdminInfoByIds")
    @ApiOperation("根据adminId集合批量查询工作人员信息")
    public Result<List<AdminInfo>> selectAdminInfoByIds(@RequestBody Set<Integer> adminIds) {
        List<AdminInfo> adminInfoList = adminInfoService.selectAdminInfoByIds(adminIds);
        return new Result<List<AdminInfo>>().setData(adminInfoList).setMsg("批量查询成功");
    }

    @GetMapping("/selAll")
    @ApiOperation("查询所有工作人员信息")
    public Result<List<AdminInfo>> selAll() {
        List<AdminInfo> adminInfoList = adminInfoService.selAll();
        return new Result<List<AdminInfo>>().setData(adminInfoList).setMsg("查询成功").setCode(200);
    }

    @GetMapping("/getAdminsByAdminIdAndRole")
    @ApiOperation("查询相同站点的所有临时工信息")
    public Result<List<AdminInfo>> getAdminsByAdminIdAndRole(@RequestHeader String token) {
        Integer adminId = tokenUtil.getAdminId(token);
        List<AdminInfo> adminInfoList = adminInfoService.getAdminsByAdminIdAndRole(adminId);
        return new Result<List<AdminInfo>>().setData(adminInfoList).setMsg("查询成功");
    }

    @PostMapping("/addNewUser")
    @ApiOperation("负责人新增临时工")
    public Result addNewUser(@RequestBody AddNewUserForm addNewUserForm, @RequestHeader String token){
        Integer adminId =tokenUtil.getAdminId(token);
        adminInfoService.addNewUser(addNewUserForm, adminId);
        return Result.getResult().setMsg("新增成功");
    }

    @GetMapping("/getCustomerService")
    @ApiOperation("随机获取客服id")
    public Result<Integer> getCustomerService(@ApiParam (value = "用户id") @RequestParam("userId") Integer userId){
        Integer customerServiceId = adminInfoService.getCustomerService();
        return new Result<Integer>().setData(customerServiceId).setMsg("获取客服成功");
    }

    @PutMapping("/updatePassword")
    @ApiOperation("修改密码")
    public Result updatePassword(@RequestBody UpdatePasswordForm updatePasswordForm, @RequestHeader String token) {
        // 从 token 中获取 adminId
        Integer adminId = tokenUtil.getAdminId(token);

        // 修改密码
        boolean isSuccess = adminInfoService.updatePassword(adminId, updatePasswordForm);
        if (isSuccess) {
            return Result.getResult().setMsg("密码修改成功");
        } else {
            return Result.getResult().setMsg("密码修改失败").setCode(400);
        }
    }
}
